<template>
  <div>
    <!-- 使用组件  并传入必选属性 -->
    <MyHeader title="商品列表">
    </MyHeader>
    <MyTable :list="list">
      <template #header >
       <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="{row}">
        <td> {{row.id}} </td>
        <td>{{row.goods_name}}</td>
        <td>{{row.goods_price}}</td>
        <td>
          <input 
          v-focus
          v-model="row.inputValue"
          v-if="row.inputVisible"
          @keydown.esc="row.inputValue=''"
          @keydown.enter="add(row)"
          @blur="row.inputVisible=false"
          style="width:100px"
          placeholder="回车添加"
          type="text">
          <button  
          v-if="!row.inputVisible"
          @click="row.inputVisible=true"
          class="btn btn-primary btn-sm add-tag"
          >添加标签</button>
          <br>
          <span class="badge bg-warning text-dark" v-for="(item,index) in row.tags" :key="index"> {{item}} </span>
        </td>
        <td>
          <button @click="del(row.id)"  class="btn btn-danger btn-sm"> X </button>
        </td>
      </template >
    </MyTable>
  </div>
</template>

<script>
// 导入子组件
import MyHeader from "../components/MyHeader.vue"
import MyTable from "../components/MyTable.vue"
export default {
  // 注册组件
  components:{
    MyHeader,
    MyTable
  },

  data() {
    return {
      // 在data中定义空数组
      list:[]
    };
  },
  // 发起axios请求并赋值给list
  async created (){
   this.list = (await this.$axios.get('/api/goods')).data.data
  },

  methods: {
    del(id){
      this.list.splice( this.list.findIndex(item => item.id == id) ,1)
    },
    add(row){
      row.tags.push(row.inputValue)
      row.inputValue=''
      row.inputVisible=false
    }
  },
};
</script>

<style lang="css" scoped>
  .badge {
    margin-left: 2px;
  }
  .btn-primary{
    margin-left: 5px;
  }
</style>